<template>
  <div class="clearfix">
    <a-upload
      action="action"
      listType="picture-card"
      :fileList="fileList"
      @preview="handlePreview"
      @change="handleChange"
      :customRequest="customRequest"
      :remove="handleRemove"
      :beforeUpload="beforeUpload"
    >
      <div v-if="fileList.length < maxSize">
        <a-icon type="plus" />
        <div class="ant-upload-text">Upload</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel" :width="1200">
      <img style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import { uploadFile } from '@/api/upms/file'
export default {
  name: 'Upload',
  data () {
    return {
      previewVisible: false,
      action: process.env.VUE_APP_API_BASE_URL + '/upms/files/upload',
      maxSize: 1,
      previewImage: '',
      fileList: []
    }
  },
  methods: {
    base (maxSize, fileList) {
      this.fileList = fileList
      this.maxSize = maxSize
    },
    handleCancel () {
      this.previewVisible = false
    },
    handlePreview (file) {
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    handleChange ({ fileList }) {
      // this.fileList = fileList
      // this.$emit('catchImage', fileList)
    },
    async customRequest (data) {
      const formData = new FormData()
      formData.append('file', data.file)
      data.onProgress()
      const that = this
      uploadFile(formData).then(res => {
        data.onSuccess()
        that.fileList.push({
          uid: '-1',
          name: res.data.fileFullName,
          status: 'done',
          url: this.BaseTool.Constant.FILE_URL + res.data.url
        })
        // this.$emit('catchImage', this.fileList)
      })
    },
    handleRemove (file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
      this.$emit('catchImage', this.fileList)
      return true
    },
    beforeUpload (file, fileList) {
      const reg = /\.(jpg|png|gif)(\?.*)?$/
      return new Promise((resolve, reject) => {
        if (reg.test(file.name)) {
          resolve()
        } else {
          this.$message.error(`请上传正确的文件格式`)
          reject(new Error('请上传正确的文件格式'))
        }
      })
    }
  }
}
</script>
<style>
  /* you can make up upload button and sample style by using stylesheets */
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
  .ant-upload-btn {
    margin-top: 20px;
  }
</style>
